package com.dgut.sales.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dgut.sales.bean.Contract;
import com.dgut.sales.bean.Details;
import com.dgut.sales.bean.Goods;
import com.dgut.sales.service.ContractService;
import com.dgut.sales.service.DetailsService;
import com.dgut.sales.service.GoodsService;

@Controller
@RequestMapping("/detail")
public class detailsController {
	
	@Autowired
	private DetailsService detailsService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ContractService contractService;

	
	@ModelAttribute
	public void prepareModel(Model model) {
		model.addAttribute("details", new Details());
	}
	
	
	@GetMapping("/inputDetails/{id}")
	public String inputDetails(@PathVariable("id") Integer id, Model model) {
		model.addAttribute("contractId", id);
		model.addAttribute("details", new Details());
		return "contract/inputDetails";
	}
	
	@PostMapping("/addDetails")
	public String addDetails(@ModelAttribute Details details, Model model) {
		Goods goods = goodsService.getGoodsById(details.getGoodsId());
		if(goods.getStates().equals("上架")) {
			detailsService.addDetails(details);
			detailsService.updateMoney(details.getContractId());
			Contract contract = contractService.getContractById(details.getContractId());
			contract.setDetailsNum(contract.getDetailsNum()+1);
			contractService.updateContract(contract);
			return "redirect:/contract/getDetails/"+details.getContractId();
		}
		else {
			model.addAttribute("buyDefault", "改商品已下架");
			return "contract/inputDetails";
			
		}
	}
	
	@GetMapping("/deleteDetails/{id}")
	public String deleteDetails(@PathVariable("id") Integer id) {
		Details details = detailsService.getDetailsById(id);
		Integer contractId = details.getContractId();
		detailsService.deleteDetails(id);
		return "redirect:/contract/getDetails/" + contractId;
		
	}
	
}
